<template>
  <span class="item_msg" @click="itemCallback">
    <span v-if="getTag.mimetype === 'span' || getTag.text" v-html="parseText()"></span>
    <img
      class="web__msg--img"
      v-if="getTag.mimetype === 'image' && getData.src"
      :src="getData.src"
      :alt="alt"
      @click="showDialog({ tag: 'image' })"
      @error="handleOnError"
      @load="load('image')"
    />
    
    <div v-if="getTag.mimetype === 'video' && getData.src">
      <customVideo :src="getData.src" @load="load('video')"></customVideo>
    </div>

    <div style="min-width: 252px;" v-if="getTag.mimetype === 'audio' && getData.src">
      <custom-audio :src="getData.src" @load="load('auido')"></custom-audio>
    </div>

    <span v-if="getTag.mimetype === 'file'">
      <span>{{ getData.fileName }}</span>
      <span v-if="getData.src" @click="showDialog({ tag: 'file' })">
        <a href="javascript:;">{{ getData.src }}</a>
      </span>
    </span>

    <!-- 查看区域 -->
    <el-dialog
      v-if="['video', 'image'].includes(getTag.mimetype)"
      :visible.sync="show"
      width="40%"
      append-to-body
      :before-close="handleClose"
      class="web__dialog"
    >
      <img :src="imgSrc" v-if="imgSrc" style="width: 100%; object-fit: cover" />
      <video
        :src="videoSrc"
        v-if="videoSrc"
        style="width: 100%; object-fit: cover"
        controls="controls"
      ></video>
      <audio
        :src="audioSrc"
        v-if="audioSrc"
        style="width: 100%; object-fit: cover"
        controls="controls"
      ></audio>
    </el-dialog>
  </span>
</template>

<script>
import emojiParser from "wechat-emoji-parser";
import customAudio from "./customAudio.vue";
import customVideo from "./customVideo.vue";

export default {
  components: {
    customAudio,
    customVideo
  },
    props: {
        talk: {
            type: Object,
            default: () => ({}),
        },
    },
    data() {
        return {
            tags: ["image", "video", "audio", "file"],
            /* 查看文件详情 */
            show: false,
            imgSrc: "",
            videoSrc: "",
            audioSrc: "",
            loadState: false,
            alt: "",
            isPlay: true,
            audioDuration: "00:00",
            currentTime: "00:00"
        };
    },
    computed: {
        getTag() {
            const { text } = this.talk?.text || "";
            const msgType = this.talk.msgType;
            let mimetype = "";
            if (msgType === "1") {
                mimetype = "span";
            }
            else if (msgType === "2") {
                mimetype = "image";
            }
            else if (msgType === "3") {
                mimetype = "video";
            }
            else if (msgType === "4") {
                mimetype = "audio";
            }
            else {
                mimetype = "span";
            }
            // console.log('this.msgType1', mimetype);
            return { mimetype, text };
        },
        getData() {
            const controls = false;
            const { fileUrl, fileName } = this.talk || {};
            return {
                src: fileUrl,
                fileName,
                controls,
            };
        },
    },
    methods: {
        load(type) {
          if (this.loadState)
              return;
          this.loadState = true;
          this.$emit("loadDone", { type, target: this.talk?.text?.text });
        },
        handleClose(done) {
            this.imgSrc = undefined;
            this.videoSrc = undefined;
            this.audioSrc = undefined;
            done();
        },
        showDialog({ tag }) {
            const { src } = this.getData;
            const callback = () => {
                if (tag === "image") {
                    this.imgSrc = src;
                    this.show = true;
                }
                else if (tag === "video") {
                    this.videoSrc = src;
                    this.show = true;
                }
                else if (tag === "audio") {
                    this.audioSrc = src;
                    this.show = true;
                }
                else if (tag === "file") {
                    window.open(src);
                }
            };
            if (typeof this.beforeOpen === "function") {
                this.beforeOpen({ tag, src }, callback);
            }
            else {
                callback();
            }
        },
        itemCallback() {
            this.$emit("systemEvent", this.talk?.text);
        },
        parseText() {
            let { text } = this.talk?.text || " ";
            if (!text)
                return;
            text = text.replace(/\n/g, "<br/>");
            let html = emojiParser(text).replace(/<img src/g, "<img data-class=\"iconBox\" src");
            html = html.replace("https://res.wx.qq.com/wxdoc/dist/assets/img/emoji-sprite.b5bd1fe0.png", "https://codegi.gitee.io/chat/emoji-sprite.png");
            return html;
        },
        parseFile() {
            let html = "";
            html +=
                "<span id=\"downLoadMsg\" class=\"msgFileContent\" data-menu=\"selMsg\"  data-data=\"" + MsgNum + "," +
                    msgType +
                    "\"<a href=\"http://" + nginxIp + ":" + msg.url + "\"><span  class=\"downFiles\">" + showFileName + "</span><img  class=\"msgFilesImg\" src=\"./images/message/docImg.png\" alt=\"\"></a></span>";
            return html;
        },
        handleOnError(e) {
            // console.log('error', e);
            this.alt = "图片加载失败";
        },
        videoPlay(e) {
            // console.log('play', e);
            this.isPlay = false;
        },
        handleVidoePlay(e) {
            this.$refs.video.play();
        },
        videoPause(e) {
            this.isPlay = true;
        },
        audioLoad(e) {
            const audioElement = this.$refs.audio;
            if (audioElement) {
                this.audioDuration = this.formatDuration(audioElement.duration);
            }
        },
        auidoPlay(e) {
            this.isPlay = true;
        },
        auidoPause(e) {
            this.isPlay = true;
        },
        handleAudioPlay(e) {
            this.$refs.audio.play();
        },
        handleTimeUpdate(e) {
            const audioElement = this.$refs.audio;
            if (audioElement) {
                this.currentTime = this.formatDuration(audioElement.currentTime);
            }
        },
        formatDuration(duration) {
            const minutes = Math.floor(duration / 60);
            const seconds = Math.floor(duration % 60);
            return `${this.padNumber(minutes)}:${this.padNumber(seconds)}`;
        },
        padNumber(num) {
            return num.toString().padStart(2, "0");
        },
    },
    mounted() {
        const type = this.getTag;
        if (this.tags.includes(type))
            return;
        this.$nextTick(() => {
            this.$emit("loadDone", { type, target: this.talk?.text });
        });
    },
};
</script>
<style lang="scss" scoped>
.item_msg {
  padding: 0px;
  margin: 0px;
  display: inline-block;
  display: flex;
  flex-direction: column;
  .web__msg--img,
  .web__msg--video,
  .web__msg--file {
    max-width: 250px;
    min-width: 50px;
    min-height: 50px;
    width: 100%;
    // margin: 10px 0;
    // border: 1px solid #eee;
    overflow: hidden;
    border-radius: 5px;
    cursor: pointer;
    display: block;
  }
  .web__msg--img[data-class="iconBox"] {
    max-width: 24px;
    min-width: unset;
    border: none;
    margin: 0;
    vertical-align: bottom;
    display: inline-block;
  }
}


</style>
